package com.quzi.kettle.activitise.main;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Selection;
import android.text.Spannable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.httprequest.AsyncBean;
import com.example.httprequest.AsyncHttpUtilClient;
import com.loopj.android.http.Base64;
import com.loopj.android.http.RequestParams;
import com.quzi.kettle.MyApplication;
import com.quzi.kettle.R;
import com.quzi.kettle.activitise.BaseActivity;
import com.quzi.kettle.activitise.process.LoginActivity;
import com.quzi.kettle.api.response.BooleanResponse;
import com.quzi.kettle.api.response.IconResponse;
import com.quzi.kettle.api.response.UserResponse;
import com.quzi.kettle.bean.http.IconString;
import com.quzi.kettle.bean.http.User;
import com.quzi.kettle.utils.ImageUtils;
import com.quzi.kettle.utils.MSharePerference;
import com.quzi.kettle.view.TitleBarView;

public class UserInfo extends BaseActivity implements
		android.view.View.OnClickListener {

	private final static int TAKEPHOTO = 0;
	private final static int CHOOSEPHOTO = 1;

	private ImageView image;
	private Button button;

	private RelativeLayout nick_name;
	private RelativeLayout gendar;
	private RelativeLayout password;
	private int photo_src = 0;
	boolean flag = false;
	private TextView tv_nickname;

	private void userInfoRequest(Map<String, String> request) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("nick_name",
				currUser.getNick_name().isEmpty() ? " " : currUser
						.getNick_name());
		// map.put("birthday", currUser.getBirthday());
		map.put("gendar", currUser.getGendar() + "");
		// map.put("email", currUser.getEmail());
		map.putAll(request);

		AsyncHttpUtilClient.request(
				getApplicationContext(),
				new AsyncBean(AsyncHttpUtilClient.POST,
						MyApplication.url
								+ MyApplication.requestMap
										.get(MyApplication.USER_INFO),
						MyApplication.header, new RequestParams(map)),
				new UserResponse<User>() {

					@Override
					public void onSuccess(User t) {

						updateUser(t);
						dissLoadingDialog();
						dialog.dismiss();
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						dialog.dismiss();
						UIHandler.obtainMessage(TOASTMSG, "失败").sendToTarget();
					}
				});
	}

	@Override
	protected void initTitleBar() {

		super.initTitleBar();
		titleBarView.setTitle(getResources().getString(R.string.persionalinfo));
	}

	protected void updateUser(User t) {
		String nick_name = t.getNick_name();
		int gendar = t.getGendar();
		String email = t.getEmail();
		String birthday = t.getBirthday();
		currUser.setGendar(gendar);
		currUser.setNick_name(nick_name);
		currUser.setEmail(email);
		currUser.setBirthday(birthday);

		// update
		curr_gendar.setText(gendar == 0 ? "男" : "女");
		curr_nick_name.setText(nick_name);
		BaseActivity.currUser.setNick_name(nick_name);
	}

	TitleBarView titleBarView;
	TextView curr_nick_name, curr_gendar;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.layout_userinfo);
		image = (ImageView) findViewById(R.id.usericon);
		button = (Button) findViewById(R.id.logout);

		nick_name = (RelativeLayout) findViewById(R.id.RelativeLayout1);
		gendar = (RelativeLayout) findViewById(R.id.RelativeLayout01);
		password = (RelativeLayout) findViewById(R.id.RelativeLayout02);

		curr_nick_name = (TextView) findViewById(R.id.tv_nickname);
		curr_gendar = (TextView) findViewById(R.id.tv_gendar);

		titleBarView = (TitleBarView) findViewById(R.id.titlebar);
		initTitleBar();

		updateUser(currUser);

		nick_name.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				View view = View.inflate(UserInfo.this,
						R.layout.dialog_update_nickname, null);

				TextView confirm = (TextView) view.findViewById(R.id.confirm);
				final EditText name = (EditText) view
						.findViewById(R.id.nick_name);
				name.setText(curr_nick_name.getText() + "");
				name.setSelection(name.getText().toString().length());
				// name.setHint(currUser.getNick_name());
				confirm.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {

						if (!name.getText().toString().isEmpty()) {
							Map<String, String> request = new HashMap<String, String>();
							request.put("nick_name", name.getText().toString());
							userInfoRequest(request);
						} else {
							dialog.dismiss();
						}
					}
				});
				showDialog(UserInfo.this, view);

			}
		});

		gendar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				View view = View.inflate(UserInfo.this, R.layout.dialog_for_me,
						null);
				TextView man = (TextView) view.findViewById(R.id.man);
				TextView woman = (TextView) view.findViewById(R.id.woman);
				TextView cancel = (TextView) view.findViewById(R.id.cancel);

				woman.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {

						showLoadingDialog();
						Map<String, String> request = new HashMap<String, String>();
						request.put("gendar", User.WOMAN + "");
						userInfoRequest(request);
					}

				});
				man.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {

						showLoadingDialog();
						Map<String, String> request = new HashMap<String, String>();
						request.put("gendar", User.MAN + "");
						userInfoRequest(request);
					}
				});

				cancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {

						dialog.dismiss();
					}
				});

				showDialog(UserInfo.this, view);
			}
		});

		password.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				nextActivity(UpdatePswActivity.class);
			}
		});
		String filePath = Environment.getExternalStorageDirectory()
				+ "/kettle/icon.png";
		Log.d("Image_kettle", "onCreate a ");
		try {
			File file = new File(filePath);
			Bitmap bitmap = ImageUtils.getImageFromLocal(filePath);
			image.setImageBitmap(ImageUtils.getRoundedCornerBitmap(bitmap));
		} catch (Exception e) {
			e.printStackTrace();
		}

		button.setOnClickListener(new android.view.View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				finish();
				MSharePerference.getInstance(getApplicationContext())
						.updateBoolean("isCheck", false);
				nextActivity(LoginActivity.class);
			}
		});

		image.setOnClickListener(new android.view.View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				final com.quzi.kettle.utils.AlertDialog dialog = new com.quzi.kettle.utils.AlertDialog(
						UserInfo.this);
				dialog.setTitle("请选择图片啊来源");
				dialog.takePhoto(new OnClickListener() {

					@Override
					public void onClick(View arg0) {

						Log.v("test", "bt_takephoto");
						// 拍照
						Intent intent2 = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);
						intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri
								.fromFile(new File(Environment
										.getExternalStorageDirectory(),
										"head.jpg")));
						startActivityForResult(intent2, 2);// 采用ForResult打开
						dialog.dismiss();
						// photo_src = TAKEPHOTO;
						// try {
						// // 拍照我们用Action为MediaStore.ACTION_IMAGE_CAPTURE，
						// // 有些人使用其他的Action但我发现在有些机子中会出问题，所以优先选择这个
						// Intent intent = new Intent(
						// MediaStore.ACTION_IMAGE_CAPTURE);
						// intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
						// startActivityForResult(intent, 1);
						// dialog.dismiss();
						// } catch (Exception e) {
						// e.printStackTrace();
						// }
					}
				});

				dialog.choosePhoto(new OnClickListener() {

					@Override
					public void onClick(View arg0) {

						// photo_src = CHOOSEPHOTO;
						// Intent intent = new
						// Intent(Intent.ACTION_GET_CONTENT);
						// intent.addCategory(Intent.CATEGORY_OPENABLE);
						// intent.setType("image/*");
						// startActivityForResult(
						// Intent.createChooser(intent, "选择图片"),
						// SELECT_PICTURE);
						// dialog.dismiss();

						Log.v("test", "bt_localphoto");
						// 选择本地图片
						Intent intent1 = new Intent(Intent.ACTION_PICK, null);
						intent1.setDataAndType(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
								"image/*");
						startActivityForResult(intent1, 1);
						dialog.dismiss();
					}
				});

			}
		});

		DownLoadBmp();

	}

	int SELECT_PICTURE = 0;
	int SELECT_CAMER = 1;

	@Override
	public void onClick(View view) {

		switch (view.getId()) {
		case R.id.usericon:
			break;
		}
	}

	/**
	 * 调用系统的裁剪
	 * 
	 * @param uri
	 */
	public void cropPhoto(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	private void DownLoadBmp() {
		Map<String, String> request = new HashMap<String, String>();
		request.put("uuid", MyApplication.UUID);
		AsyncHttpUtilClient.request(
				getApplicationContext(),
				new AsyncBean(AsyncHttpUtilClient.GET,
						MyApplication.url
								+ MyApplication.requestMap
										.get(MyApplication.USER_ICON),
						MyApplication.header, new RequestParams(request)),
				new IconResponse<IconString>() {

					@Override
					public void onSuccess(IconString t) {

						byte[] icon = Base64.decode(t.getIcon(), 0);

						String filePath = Environment
								.getExternalStorageDirectory()
								+ "/kettle/icon.png";
						Log.d("Image_kettle", "获取图片成功");
						try {
							File file = new File(filePath);
							file.delete();
						} catch (Exception e) {
							e.printStackTrace();
						}
						Log.d("quzi", "filePath  +" + filePath);
						if (!new File(filePath).getParentFile().exists()) {
							new File(filePath).getParentFile().mkdirs();
						}
						try {
							ImageUtils.saveImage(filePath, icon);
						} catch (IOException e) {

							e.printStackTrace();
						}
						if (bmp != null) {
							bmp.recycle();
						}
						// bmp = ImageUtils.getImageFromLocal(filePath);
						// image.setImageBitmap(ImageUtils
						// .getRoundedCornerBitmap(bmp));
					}

					@Override
					public void onFailure(int arg0, String arg1) {

					}
				});
	}

	private Bitmap bmp = null;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case 1:
			if (resultCode == RESULT_OK) {
				cropPhoto(data.getData());// 裁剪图片
			}
			break;
		case 2:
			if (resultCode == RESULT_OK) {
				File temp = new File(Environment.getExternalStorageDirectory()
						+ "/head.jpg");
				cropPhoto(Uri.fromFile(temp));// 裁剪图片
			}
			break;
		case 3:
			if (data != null) {
				Log.v("photo", "in the 3");
				Bundle extras = data.getExtras();
				bmp = extras.getParcelable("data");
				if (bmp != null) {
					flag = true;
					/**
					 * 上传服务器代码
					 */
					// if (bmp != null) // 如果不释放的话，不断取图片，将会内存不够
					// bmp.recycle();
					// bmp = ImageUtils.zoomImageWithnewWidth(head, 300);
					image.setImageBitmap(ImageUtils.getRoundedCornerBitmap(bmp));
					Map<String, String> request = new HashMap<String, String>();
					String picture = Base64.encodeToString(
							ImageUtils.bitmap2Bytes(bmp), 0);
					request.put("icon", picture);
					AsyncHttpUtilClient.doPost(
							AsyncHttpUtilClient.POST,
							MyApplication.url
									+ MyApplication.requestMap
											.get(MyApplication.USER_ICON),
							MyApplication.header, new RequestParams(request),
							new BooleanResponse<Boolean>() {

								@Override
								public void onSuccess(Boolean t) {
									if (flag) {
										UIHandler.obtainMessage(TOASTMSG,
												"上传成功").sendToTarget();
										flag = false;
									}
									String filePath = Environment
											.getExternalStorageDirectory()
											+ "/kettle/icon.png";
									try {
										ImageUtils.saveImage(filePath,
												ImageUtils.bitmap2Bytes(bmp));
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									// DownLoadBmp();
									// updateUserIcon(Constant.user,
									// BitmapUtils.getHeadFile("testhead"));
									// BitmapUtils.saveBitmaptoJpgLocal(
									// head,
									// getApplicationContext(),
									// getResources().getString(
									// R.string.insert_sdcard));

								}

								@Override
								public void onFailure(int arg0, String arg1) {
									UIHandler.obtainMessage(TOASTMSG, "上传失败")
											.sendToTarget();
								}
							});
				}

			}
			break;

		}

	}
}
// super.onActivityResult(requestCode, resultCode, data);
//
// Log.d("kettlt-wdfewr", "requestCode = " + requestCode
// + "  resultCode = " + resultCode + "   data = " + data);
//
// if (resultCode == RESULT_OK) {
// // 保存图片
// String filePath = Environment.getExternalStorageDirectory()
// + "/kettle/icon.png";
// try {
// ImageUtils.saveImage(filePath, ImageUtils.bitmap2Bytes(bmp));
// Log.d("Image_kettle", "保存图片");
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// switch (photo_src) {
// case TAKEPHOTO:
// if (bmp != null) // 如果不释放的话，不断取图片，将会内存不够
// bmp.recycle();
//
// bmp = (Bitmap) data.getExtras().get("data");
// bmp = CompressImageUtil.comp(bmp);
//
// break;
// case CHOOSEPHOTO:
// Uri uri = data.getData();
// ContentResolver cr = this.getContentResolver();
// try {
// if (bmp != null) // 如果不释放的话，不断取图片，将会内存不够
// bmp.recycle();
//
// bmp = BitmapFactory.decodeStream(cr.openInputStream(uri));
// bmp = CompressImageUtil.comp(bmp);
// } catch (FileNotFoundException e) {

// e.printStackTrace();
// }
// break;
// }
//
// String picture = Base64.encodeToString(
// ImageUtils.bitmap2Bytes(bmp), 0);
//
// Log.d("Image_kettle", "获取图片成功");
// try {
// File file = new File(filePath);
// file.delete();
// } catch (Exception e) {
// e.printStackTrace();
// }
// Log.d("quzi", "filePath  +" + filePath);
// if (!new File(filePath).getParentFile().exists()) {
// new File(filePath).getParentFile().mkdirs();
// }
// try {
// ImageUtils.saveImage(filePath, picture.getBytes());
// } catch (IOException e) {

// e.printStackTrace();
// }
//
// Map<String, String> request = new HashMap<String, String>();
// request.put("icon", picture);
// AsyncHttpUtilClient.doPost(
// AsyncHttpUtilClient.POST,
// MyApplication.url
// + MyApplication.requestMap
// .get(MyApplication.USER_ICON),
// MyApplication.header, new RequestParams(request),
// new BooleanResponse<Boolean>() {
//
// @Override
// public void onSuccess(Boolean t) {

// UIHandler.obtainMessage(TOASTMSG, "上传成功")
// .sendToTarget();
// // DownLoadBmp();
// }
//
// @Override
// public void onFailure(int arg0, String arg1) {
// UIHandler.obtainMessage(TOASTMSG, "上传失败")
// .sendToTarget();
// }
//
// });
// image.setImageBitmap(ImageUtils.getRoundedCornerBitmap(bmp));
// } else {
// Toast.makeText(UserInfo.this, "请重新选择图片", Toast.LENGTH_SHORT).show();
// }